<template>
  <el-drawer
    :title="isEditing ? '编辑数据模型' : '添加数据模型'"
    v-model="dialogVisible"
    size="60%"
    direction="rtl"
    @closed="handleDialogClosed"
  >
    <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
      <el-form-item label="模型名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入模型名称" />
      </el-form-item>
      <el-form-item label="接口标识" prop="apiModel">
        <el-input v-model="form.apiModel" placeholder="请输入接口标识" />
      </el-form-item>
      <el-form-item label="数据表名" prop="tableName">
        <el-input v-model="form.tableName" placeholder="请输入数据表名" />
      </el-form-item>
      <el-form-item label="模型分类" prop="catalog">
        <tree-select :fetch="false" api-prefix="moduleCatalog" v-model="form.catalog" placeholder="请输入模型分类" />
      </el-form-item>
      <el-form-item label="模型描述">
        <el-input type="textarea" v-model="form.description" rows="3" placeholder="请输入模型描述" />
      </el-form-item>

      <el-divider>字段定义</el-divider>

      <div class="fields-container">
        <div class="fields-header">
          <el-button type="primary" size="small" @click="showAiFieldGenerator">
            <el-icon><Cpu /></el-icon> AI 生成字段
          </el-button>
          <el-button type="primary" size="small" @click="addField">
            <el-icon><Plus /></el-icon> 添加字段
          </el-button>
        </div>

        <el-table :data="visibleItems" border style="width: 100%" :row-class-name="getRowClassName">
          <el-table-column label="显示名称" prop="name" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="显示名称" />
            </template>
          </el-table-column>
          <el-table-column label="程序变量" prop="name" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.javaName" placeholder="字段名" />
            </template>
          </el-table-column>
          <el-table-column label="字段名" prop="columnName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.columnName" placeholder="字段名" />
            </template>
          </el-table-column>
          <el-table-column label="数据类型" prop="type" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.dataType" placeholder="选择类型">
                <el-option label="字符串" :value="1" />
                <el-option label="整数" :value="2" />
                <el-option label="浮点数" :value="5" />
                <el-option label="布尔值" :value="6" />
                <el-option label="日期" :value="9" />
                <el-option label="时间戳" :value="8" />
                <el-option label="JSON" :value="17" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否必填" prop="required" width="90" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.required" :inactive-value="-1" :active-value="1" />
            </template>
          </el-table-column>
          <el-table-column label="持久化" prop="persistent" width="90" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.persistent" :inactive-value="-1" :active-value="1" />
            </template>
          </el-table-column>
          <el-table-column label="描述" prop="comment">
            <template #default="scope">
              <el-input v-model="scope.row.comment" placeholder="字段描述" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" @click="editField(scope.$index)" style="margin-right: 8px;">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button type="danger" size="small" @click="removeField(scope.$index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveModel">保存</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- AI 字段生成组件 -->
  <ai-field-generator
    v-model:visible="showAiDialog"
    :model-name="form.name"
    :table-name="form.tableName"
    :description="form.description"
    :existing-fields="form.items || []"
    @apply-fields="handleApplyFields"
  />

  <!-- 字段编辑组件 -->
  <field-editor
    v-if="showFieldEditor"
    v-model:visible="showFieldEditor"
    :field="currentField"
    :is-editing="isEditingField"
    @save="handleFieldSave"
  />
</template>

<script setup>
import {ref, computed, watch, onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete, Cpu, Edit } from '@element-plus/icons-vue'
import http from '@/utils/request.js'
import AiFieldGenerator from './AiFieldGenerator.vue'
import FieldEditor from './FieldEditor.vue'
import {postData, postList} from "@/uses/handleData.js";
import TreeSelect from "@/components/TreeSelect.vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  model: {
    type: Object,
    default: () => ({})
  },
  isEditing: {
    type: Boolean,
    default: false
  },

})

const emit = defineEmits(['update:visible', 'saved'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 表单引用
const formRef = ref(null)

// 表单数据
const form = ref({
  id: null,
  name: '',
  apiModel: '',
  tableName: '',
  catalog: null,
  description: '',
  items: []
})

// 错误行索引
const errorRowIndexes = ref(new Set())

// 计算可见的字段项（过滤掉状态为2的项）
const visibleItems = computed(() => {
  return form.value.items ? form.value.items.filter(item => item.state !== 2) : []
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
  ],
  tableName: [
    { required: true, message: '请输入数据表名', trigger: 'blur' },
  ],
  catalog: [
    { required: true, message: '请选择模型分类', trigger: 'change' },
  ]
}

// AI 生成相关
const showAiDialog = ref(false)

// 字段编辑相关
const showFieldEditor = ref(false)
const currentField = ref({})
const currentFieldIndex = ref(-1)
const isEditingField = ref(false)

// 显示AI字段生成器
const showAiFieldGenerator = () => {
  showAiDialog.value = true
}

// 处理应用AI生成的字段
const handleApplyFields = (fields) => {
  if (!form.value.items) {
    form.value.items = []
  }

  // 过滤已存在的字段（基于字段名和数据库字段名）
  const existingFieldNames = form.value.items
    .filter(item => item.state !== 2) // 排除已删除的字段
    .map(item => ({
      name: item.name?.toLowerCase(),
      columnName: item.columnName?.toLowerCase(),
      javaName: item.javaName?.toLowerCase()
    }))

  const newFields = fields.filter(field => {
    const fieldName = field.name?.toLowerCase()
    const columnName = field.columnName?.toLowerCase()
    const javaName = field.javaName?.toLowerCase()
    
    return !existingFieldNames.some(existing => 
      existing.name === fieldName || 
      existing.columnName === columnName || 
      existing.javaName === javaName
    )
  })

  if (newFields.length < fields.length) {
    const filteredCount = fields.length - newFields.length
    ElMessage.info(`已过滤 ${filteredCount} 个重复字段`)
  }

  // 处理字段数据格式
  const processedFields = newFields.map(field => {
    // 如果字段已经是完整的格式（来自SQL解析），直接使用
    if (field.columnName && field.dataType !== undefined) {
      return {
        id: null,
        name: field.name || '',
        javaName: field.javaName || '',
        columnName: field.columnName || '',
        dataType: field.dataType,
        required: field.required !== undefined ? field.required : -1,
        unique: field.unique || 0,
        persistent: field.persistent !== undefined ? field.persistent : 1,
        detailState: field.detailState !== undefined ? field.detailState : -1,
        relatedModule: field.relatedModule || null,
        foreignState: field.foreignState !== undefined ? field.foreignState : -1,
        state: field.state !== undefined ? field.state : 1,
        defaultValue: field.defaultValue || '',
        comment: field.comment || '',
        validation: field.validation || ''
      }
    } else {
      // 处理AI生成的字段格式
      return {
        id: null,
        name: field.name || '',
        javaName: field.name ? field.name.replace(/\s+/g, '').replace(/^./, str => str.toLowerCase()) : '',
        columnName: field.name ? field.name.toLowerCase().replace(/\s+/g, '_') : '',
        dataType: field.type === 'string' ? 1 :
                  field.type === 'integer' ? 2 :
                  field.type === 'float' ? 5 :
                  field.type === 'boolean' ? 6 :
                  field.type === 'date' ? 9 :
                  field.type === 'timestamp' ? 8 :
                  field.type === 'json' ? 17 : 1,
        required: field.required ? 1 : -1,
        unique: 0,
        persistent: 1,
        detailState: -1,
        relatedModule: null,
        foreignState: -1,
        state: 1,
        defaultValue: field.defaultValue || '',
        comment: field.description || '',
        validation: ''
      }
    }
  })

  // 添加新字段到现有字段列表
  form.value.items.push(...processedFields)

  ElMessage.success(`成功添加 ${processedFields.length} 个字段`)
}








// 直接使用 props.model 初始化表单
const initForm = () => {
  if (props.isEditing && props.model && Object.keys(props.model).length > 0) {
    // 编辑模式，使用传入的模型数据
    form.value = {
      id: props.model.id,
      name: props.model.name || '',
      apiModel: props.model.apiModel || '',
      tableName: props.model.tableName || '',
      catalog: props.model.catalog || null,
      description: props.model.description || props.model.note || '',
      items: props.model.items || []
    }
  } else {
    // 添加模式，初始化表单
    form.value = {
      id: null,
      name: '',
      apiModel: '',
      tableName: '',
      catalog: null,
      description: '',
      items: []
    }
  }
}

// 添加字段
const addField = () => {
  if (!form.value.items) {
    form.value.items = []
  }
  form.value.items.push({
    id: null,
    name: '',
    javaName: '',
    columnName: '',
    dataType: 1,
    required: -1,
    unique: 0,
    persistent: -1,
    detailState: -1,
    relatedModule: null,
    foreignState: -1,
    state: 1,
    defaultValue: '',
    comment: '',
    validation: ''
  })
}

// 编辑字段
const editField = (index) => {
  // 需要找到在原始数组中的真实索引
  const visibleItem = visibleItems.value[index]
  const realIndex = form.value.items.findIndex(item => item === visibleItem)

  if (realIndex >= 0) {
    currentField.value = { ...form.value.items[realIndex] }
    currentFieldIndex.value = realIndex
    isEditingField.value = true
    showFieldEditor.value = true
  }
}

// 处理字段保存
const handleFieldSave = (fieldData) => {
  if (isEditingField.value && currentFieldIndex.value >= 0) {
    // 编辑模式：更新现有字段
    form.value.items[currentFieldIndex.value] = { ...fieldData }
  } else {
    // 添加模式：添加新字段
    if (!form.value.items) {
      form.value.items = []
    }
    form.value.items.push({ ...fieldData })
  }

  // 清空错误标记
  errorRowIndexes.value.clear()

  // 重置状态
  currentField.value = {}
  currentFieldIndex.value = -1
  isEditingField.value = false
}

// 删除字段（设置状态为2）
const removeField = (index) => {
  // 需要找到在原始数组中的真实索引
  const visibleItem = visibleItems.value[index]
  const realIndex = form.value.items.findIndex(item => item === visibleItem)

  if (realIndex >= 0) {
    // 设置状态为2，表示已删除
    form.value.items[realIndex].state = 2
    // 清空错误标记
    errorRowIndexes.value.clear()
  }
}

// 保存模型
const saveModel = async () => {
  if (!form.value.name || !form.value.tableName || !form.value.catalog) {
    ElMessage.warning('请填写必填项')
    return
  }

  // 验证字段（只验证可见的字段）
  const activeItems = form.value.items ? form.value.items.filter(item => item.state !== 2) : []
  if (activeItems.length === 0) {
    ElMessage.warning('请至少添加一个字段')
    return
  }

  // 清空之前的错误标记
  errorRowIndexes.value.clear()

  // 检查字段名是否重复（只检查可见的字段）
  const columnNames = []
  const javaNames = []
  const columnNameIndexes = {}
  const javaNameIndexes = {}

  for (let i = 0; i < activeItems.length; i++) {
    const field = activeItems[i]
    const originalIndex = form.value.items.findIndex(item => item === field)

    if (!field.columnName || !field.dataType) {
      errorRowIndexes.value.add(originalIndex)
      ElMessage.warning('字段名称和类型不能为空')
      return
    }

    // 检查数据库字段名重复
    if (columnNames.includes(field.columnName)) {
      // 标记当前行和之前重复的行
      errorRowIndexes.value.add(originalIndex)
      errorRowIndexes.value.add(columnNameIndexes[field.columnName])
      ElMessage.warning(`字段名 "${field.columnName}" 重复，请修改后再提交`)
      return
    }
    columnNames.push(field.columnName)
    columnNameIndexes[field.columnName] = originalIndex

    // 检查Java变量名重复
    if (field.javaName && javaNames.includes(field.javaName)) {
      // 标记当前行和之前重复的行
      errorRowIndexes.value.add(originalIndex)
      errorRowIndexes.value.add(javaNameIndexes[field.javaName])
      ElMessage.warning(`程序变量 "${field.javaName}" 重复，请修改后再提交`)
      return
    }
    if (field.javaName) {
      javaNames.push(field.javaName)
      javaNameIndexes[field.javaName] = originalIndex
    }
  }

  // catalog 现在是字符串类型
  let catalogId = form.value.catalog

  try {
    // 将字段转换为items格式


    let res
    if (props.isEditing) {
      res = await http.post('/module/update', form.value)
    } else {
      res = await http.post('/module/create', form.value)
    }

    if (res.code === 200) {
      ElMessage.success(props.isEditing ? '模型更新成功' : '模型添加成功')

      // 调用 updateTable 接口更新数据表结构
      try {
        const updateTableData = {
          id: res.data?.id || form.value.id, // 使用返回的ID或表单中的ID
        }
        const updateTableRes = await http.post('/module/updateTable', updateTableData)
        if (updateTableRes.code === 200) {
          ElMessage.success('数据表结构更新成功')
        } else {
          ElMessage.warning(`模型保存成功，但数据表更新失败: ${updateTableRes.message || '未知错误'}`)
        }
      } catch (updateTableError) {
        console.error('更新数据表结构出错:', updateTableError)
        ElMessage.warning('模型保存成功，但数据表更新失败，请检查网络连接')
      }

      dialogVisible.value = false
      emit('saved')
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('保存模型出错:', error)
    ElMessage.error('操作失败，请检查网络连接')
  }
}

// 获取行的CSS类名
const getRowClassName = ({ rowIndex }) => {
  return errorRowIndexes.value.has(rowIndex) ? 'error-row' : ''
}

// 对话框关闭时重置表单
const handleDialogClosed = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 清空错误标记
  errorRowIndexes.value.clear()
  form.value = {
    id: null,
    name: '',
    apiModel: '',
    tableName: '',
    catalog: null,
    description: '',
    items: []
  }
}


onMounted(async () => {
  // 初始化表单
  initForm()

  // 如果是编辑模式，加载模型项目列表
  if (props.isEditing && props.model && props.model.id) {
    let param = {};
    param.moduleId = props.model.id;
    let res = await postList("module_item_list", param);
    if (res.code===200){
      form.value.items = res.data;
    }
  }
})

</script>

<style scoped>
.fields-container {
  margin-top: 20px;
}

.fields-header {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-drawer__body) {
  padding: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}



/* 抽屉底部按钮样式 */
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}

/* 错误行样式 */
:deep(.error-row) {
  background-color: #fef0f0 !important;
}

:deep(.error-row:hover) {
  background-color: #fde2e2 !important;
}

/* 表格头部居中样式 */
:deep(.el-table th .cell) {
  text-align: center;
}
</style>
